﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Surging.Core.CPlatform.Ioc;

namespace Gmmy.RepositoryExtension
{
    public class UnitOfWorkFramework<D>: ServiceBase, IUnitOfWork
        where D : DbContext, new()
    {

        private D _dataContext;
        protected D DataContext => _dataContext ?? (_dataContext = DatabaseFactory.Get());

        public UnitOfWorkFramework(IDatabaseFrameworkFactory<D> databaseFactory)
        {
            DatabaseFactory = databaseFactory;
        }

        protected IDatabaseFrameworkFactory<D> DatabaseFactory
        {
            get;
            private set;
        }
        public async Task CommitAsync()
        {
            try
            {
                await DataContext.SaveChangesAsync();
            }
            catch (Exception e)
            {
                throw new Exception(e.GetBaseException().Message);
            }
        }
    }
}
